package ing.gzq.service;

import ing.gzq.base.Result;
import ing.gzq.base.ResultCache;
import ing.gzq.dao.UserDao;
import ing.gzq.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static ing.gzq.model.User.STUDENT_ROLE;
import static ing.gzq.model.User.TEACHER_ROLE;
import static ing.gzq.service.AuthenticationService.getUserInSecurityContext;

/**
 * Created by gzq on 17-7-20.
 */
@Service
public class UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    PasswordEncoder bcryptEncoder;


    @Transactional
    public Result insertUser(User user) {

        if (!"student".equals(user.getType()) && !"teacher".equals(user.getType())) {
            return ResultCache.getFailureDetail("用户类型只能为student or teacher");
        }

        user.setPassword(bcryptEncoder.encode(user.getPassword()));

        userDao.insertUser(user);
        if ("student".equals(user.getType())) {
            userDao.giveAuthority(user.getUsername(), STUDENT_ROLE);
        } else {
            userDao.giveAuthority(user.getUsername(), TEACHER_ROLE);
        }
        return ResultCache.OK;

    }


    public Result modifyInfo(User user) {
        User u = getUserInSecurityContext();
        if(user.getName()!=null){
            u.setName(user.getName());
        }
        if(user.getPassword()!= null){
            u.setPassword(bcryptEncoder.encode(user.getPassword()));
        }
        try{
            userDao.updateUserInfo(u);
            return ResultCache.OK;
        }catch (Exception ex){
            ex.printStackTrace();
            return ResultCache.getFailureDetail(ex.getMessage());
        }
    }

    private boolean checkPassword(String input, String saved) {
        return bcryptEncoder.matches(input,saved);
    }
}
